// kuaishou.js
const { getApiUrl } = require('../../config/api.js')

Page({
  data: {
    videoUrl: '',
    isLoading: false,
    historyList: []
  },

  onLoad(options) {
    this.loadHistory()
    
    // 处理分享链接
    if (options.sharedUrl) {
      console.log('收到分享的快手链接:', options.sharedUrl)
      this.setData({
        videoUrl: decodeURIComponent(options.sharedUrl)
      })
      
      // 自动开始解析
      setTimeout(() => {
        this.onDownload()
      }, 500)
    }
  },

  // 输入框内容变化
  onUrlInput(e) {
    console.log('输入框内容变化:', e.detail.value)
    this.setData({
      videoUrl: e.detail.value
    })
  },

  // 粘贴按钮点击事件
  onPaste() {
    console.log('点击粘贴按钮')
    
    // 获取剪贴板内容
    wx.getClipboardData({
      success: (res) => {
        console.log('剪贴板内容:', res.data)
        const clipboardText = res.data.trim()
        
        if (clipboardText) {
          // 提取URL部分
          const extractedUrl = this.extractUrlFromText(clipboardText)
          console.log('提取的URL:', extractedUrl)
          
          if (extractedUrl) {
            // 将提取的URL设置到输入框
            this.setData({
              videoUrl: extractedUrl
            })
            
            // 显示成功提示
            wx.showToast({
              title: '已提取链接',
              icon: 'success',
              duration: 1500
            })
            
            // 自动验证链接格式
            const isValid = this.isValidKuaishouUrl(extractedUrl)
            if (isValid) {
              console.log('提取的链接格式正确')
            } else {
              console.log('提取的链接格式可能不正确')
              wx.showToast({
                title: '请确认链接格式是否正确',
                icon: 'none',
                duration: 2000
              })
            }
          } else {
            // 如果没有找到URL，显示原始内容并提示
            this.setData({
              videoUrl: clipboardText
            })
            
            wx.showToast({
              title: '未找到有效链接',
              icon: 'none',
              duration: 2000
            })
          }
        } else {
          wx.showToast({
            title: '剪贴板为空',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('获取剪贴板内容失败:', err)
        wx.showToast({
          title: '获取剪贴板内容失败',
          icon: 'none'
        })
      }
    })
  },

  // 从文本中提取URL
  extractUrlFromText(text) {
    console.log('开始提取URL，原始文本:', text)
    
    // 快手URL的正则表达式模式
    const kuaishouPatterns = [
      /https?:\/\/(?:www\.)?kuaishou\.com\/video\/\d+/g,
      /https?:\/\/v\.kuaishou\.com\/\w+/g,
      /https?:\/\/.*\.kuaishou\.com\/.*/g
    ]
    
    // 尝试匹配所有快手URL模式
    for (let pattern of kuaishouPatterns) {
      const matches = text.match(pattern)
      if (matches && matches.length > 0) {
        console.log('找到匹配的URL:', matches[0])
        return matches[0]
      }
    }
    
    // 如果没有找到完整的URL，尝试查找包含kuaishou的链接
    const keywordPattern = /https?:\/\/[^\s]*kuaishou[^\s]*/g
    const keywordMatches = text.match(keywordPattern)
    if (keywordMatches && keywordMatches.length > 0) {
      console.log('通过关键词找到URL:', keywordMatches[0])
      return keywordMatches[0]
    }
    
    console.log('未找到有效的快手URL')
    return null
  },

  // 开始下载
  onDownload() {
    const { videoUrl, isLoading } = this.data
    
    console.log('开始下载，当前输入:', videoUrl)
    console.log('是否正在加载:', isLoading)
    
    if (!videoUrl.trim()) {
      console.log('链接为空')
      wx.showToast({
        title: '请输入视频链接',
        icon: 'none'
      })
      return
    }

    if (isLoading) {
      console.log('正在加载中，跳过')
      return
    }

    // 验证链接格式
    const isValid = this.isValidKuaishouUrl(videoUrl)
    console.log('链接验证结果:', isValid)
    
    if (!isValid) {
      wx.showToast({
        title: '请输入正确的快手链接',
        icon: 'none'
      })
      return
    }

    console.log('开始解析视频')
    this.setData({ isLoading: true })
    this.parseVideo(videoUrl)
  },

  // 验证快手链接格式
  isValidKuaishouUrl(url) {
    const kuaishouPatterns = [
      /https?:\/\/(?:www\.)?kuaishou\.com\/video\/\d+/,
      /https?:\/\/v\.kuaishou\.com\/\w+/,
      /https?:\/\/.*\.kuaishou\.com\/.*/
    ]
    return kuaishouPatterns.some(pattern => pattern.test(url))
  },

  // 解析视频
  parseVideo(url) {
    console.log('开始解析视频，URL:', url)
    
    wx.showLoading({
      title: '解析中...'
    })

    const requestUrl = getApiUrl('kuaishou', 'parse')
    console.log('请求URL:', requestUrl)
    console.log('请求参数:', { url: url })

    // 调用后台API解析视频
    wx.request({
      url: requestUrl,
      method: 'GET',
      data: {
        url: url
      },
      success: (res) => {
        console.log('请求成功，响应数据:', res)
        wx.hideLoading()
        this.setData({ isLoading: false })

        if (res.data && res.data.code === 200) {
          const responseData = res.data.data
          console.log('解析成功，视频数据:', responseData)
          
          // 构造视频数据对象
          const videoData = {
            title: responseData.title || '未知标题',
            author: responseData.author || '未知作者',
            avatar: responseData.avatar || '',
            thumbnail: responseData.cover || '',
        videoUrl: responseData.url || '',
            duration: responseData.time ? this.formatDuration(responseData.time) : '',
            like: responseData.like || 0,
            originalUrl: url,
            music: responseData.music || null,
            platform: 'kuaishou'
          }
          
          // 保存到历史记录
          this.saveToHistory(videoData)
          
          // 跳转到下载页面
          wx.navigateTo({
            url: `/pages/download/download?data=${encodeURIComponent(JSON.stringify(videoData))}`
          })
        } else {
          console.log('解析失败，响应数据:', res.data)
          wx.showToast({
            title: res.data.msg || '解析失败，请重试',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('API调用失败:', err)
        wx.hideLoading()
        this.setData({ isLoading: false })
        wx.showToast({
          title: '网络错误，请检查网络连接',
          icon: 'none'
        })
      }
    })
  },

  // 保存到历史记录
  saveToHistory(videoData) {
    const historyList = wx.getStorageSync('downloadHistory') || []
    const originalTitle = videoData.title || '未知标题'
    const displayTitle = originalTitle.length > 30 ? originalTitle.substring(0, 30) + '...' : originalTitle
    
    const newItem = {
      id: Date.now(),
      title: originalTitle,
      displayTitle: displayTitle,
      thumbnail: videoData.thumbnail || '',
      url: videoData.videoUrl || videoData.url, // 兼容字段
      originalUrl: videoData.originalUrl || '',
      time: this.formatTime(new Date()),
      platform: 'kuaishou'
    }
    
    // 避免重复添加
    const exists = historyList.find(item => item.url === newItem.url)
    if (!exists) {
      historyList.unshift(newItem)
      // 最多保存20条记录
      if (historyList.length > 20) {
        historyList.splice(20)
      }
      wx.setStorageSync('downloadHistory', historyList)
      this.setData({ historyList })
    }
  },

  // 加载历史记录
  loadHistory() {
    const historyList = wx.getStorageSync('downloadHistory') || []
    // 只显示快手相关的历史记录
    const kuaishouHistoryList = historyList.filter(item => item.platform === 'kuaishou')
    // 为已有的历史记录添加displayTitle字段
    const processedHistoryList = kuaishouHistoryList.map(item => {
      if (!item.displayTitle) {
        const originalTitle = item.title || '未知标题'
        item.displayTitle = originalTitle.length > 10 ? originalTitle.substring(0, 10) + '...' : originalTitle
      }
      return item
    })
    this.setData({ historyList: processedHistoryList.slice(0, 5) })
  },

  // 点击历史记录项
  onHistoryItemTap(e) {
    const item = e.currentTarget.dataset.item
    wx.navigateTo({
      url: `/pages/download/download?data=${encodeURIComponent(JSON.stringify(item))}`
    })
  },

  // 格式化时间
  formatTime(date) {
    const now = new Date()
    const diff = now - date
    const minutes = Math.floor(diff / 60000)
    const hours = Math.floor(diff / 3600000)
    const days = Math.floor(diff / 86400000)

    if (minutes < 1) return '刚刚'
    if (minutes < 60) return `${minutes}分钟前`
    if (hours < 24) return `${hours}小时前`
    if (days < 7) return `${days}天前`
    return date.toLocaleDateString()
  },

  // 格式化时长（从时间戳转换为可读格式）
  formatDuration(timestamp) {
    const date = new Date(timestamp * 1000)
    const now = new Date()
    const diff = now - date
    const minutes = Math.floor(diff / 60000)
    const hours = Math.floor(diff / 3600000)
    const days = Math.floor(diff / 86400000)

    if (minutes < 1) return '刚刚'
    if (minutes < 60) return `${minutes}分钟前`
    if (hours < 24) return `${hours}小时前`
    if (days < 7) return `${days}天前`
    return date.toLocaleDateString()
  },

  // 分享给好友
  onShareAppMessage() {
    return {
      title: '快手视频去水印下载',
      path: '/pages/index/index',
      imageUrl: '/images/kuaishou-share.png'
    }
  },

  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: '快手视频去水印下载',
      path: '/pages/index/index',
      imageUrl: '/images/kuaishou-share.png'
    }
  }
})
